<script setup>
import {onMounted, ref} from "vue";
import {addUser, deleteUser, exportUserList, getUserList, updateUserInfo} from "@/api/user.js";
import {ElMessage, ElNotification} from "element-plus";
import UserDetailsView from "@/views/user/UserDetailsView.vue";
import {BaseUrl} from "@/utils/http.js";
import {signExport} from "@/api/sign.js";

const userList = ref([])
const addUserDrawer = ref(false)
const updateUserDrawer = ref(false)
const userDetailsDrawer = ref(false)
const newUser = ref({})

const detailUserData = ref({})

const updateUserData = ref({})

const pageForm = ref({
  page: 1,
  size: 10,
  total: 0
})

const getUserListAll = async () => {
  const list = await getUserList(pageForm.value)
  console.log(list)
  if (list.code !== 200) {
    ElNotification({
      title: '接口错误',
      message: '获取用户列表失败！',
      type: 'error',
    })
  }
  userList.value = list.data.records
  pageForm.value.total = list.data.total
  pageForm.value.page = list.data.current
  pageForm.value.size = list.data.size

}
const openAddUserDrawer = () => {
  addUserDrawer.value = true
}

const openUpdateUserDrawer = (user) => {
  updateUserDrawer.value = true
  updateUserData.value = user
}

const saveNewUser = async () => {
  const result = await addUser(newUser.value)
  if (result.code === 200) {
    ElNotification({
      title: '请求成功',
      message: '添加用户成功！',
      type: 'success',
    })
    newUser.value = {}
    addUserDrawer.value = false
    await getUserListAll()
  } else {
    ElNotification({
      title: '请求失败',
      message: '添加用户失败！',
      type: 'error',
    })
  }
}

const deleteUserById = async (id) => {
  const result = await deleteUser(id)
  if (result.code === 200) {
    ElNotification({
      title: '请求成功',
      message: '删除用户成功！',
      type: 'success',
    })
    await getUserListAll()
  } else {
    ElNotification({
      title: '请求失败',
      message: '删除用户失败！',
      type: 'error',
    })
  }
}

async function updateUserById() {
  const result = await updateUserInfo(updateUserData.value)
  if (result.code === 200) {
    ElNotification({
      title: '请求成功',
      message: '修改用户信息成功！',
      type: 'success',
    })
    updateUserDrawer.value = false
    await getUserListAll()
  } else {
    ElNotification({
      title: '请求失败',
      message: '修改用户信息失败！',
      type: 'error',
    })
  }
}

const openUserDetailsDrawer = (user) => {
  refCount.value++
  userDetailsDrawer.value = true
  detailUserData.value = user
}


onMounted(async () => {
  await getUserListAll()
})

const handleCurrentChange = (page) => {
  pageForm.value.page = page;
  // 在这里可以触发数据加载逻辑
  console.log('当前页码:', page);
  getUserListAll()
};

const handleSignExport = async () => {
  const ex = await signExport()
}

const handleUserExport = async () => {
  await exportUserList()
}

// 自定义请求头
const headers = ref({
  'access-token': localStorage.getItem('token')
});

// 文件上传成功回调
const handleUploadSuccess = (response) => {
  ElMessage.success('文件上传成功');
  console.log('服务器返回的数据:', response);
};

// 文件上传失败回调
const handleUploadError = (error) => {
  ElMessage.error('文件上传失败');
  console.error('上传错误:', error);
};

// 文件上传前的校验
const beforeUpload = (file) => {
  const isXlsx = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  const isLt10MB = file.size / 1024 / 1024 < 10;

  if (!isXlsx) {
    ElMessage.error('只能上传 .xlsx 文件');
    return false;
  }
  if (!isLt10MB) {
    ElMessage.error('文件大小不能超过 10MB');
    return false;
  }
  return true;
};

// 文件超出限制回调
const handleExceed = () => {
  ElMessage.warning('每次只能上传一个文件');
};

const uploadUrl = BaseUrl + '/user/import'

const userRole = JSON.parse(localStorage.getItem('userInfo')).role

const refCount = ref(0)
</script>

<template>
  <div class="user-operation" style="display: flex" v-if="userRole === 1">
    <el-button type="primary" size="default" @click="openAddUserDrawer">添加员工</el-button>
    <el-upload
        :action=uploadUrl
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        :headers="headers"
        accept=".xlsx"
        :limit="1"
        :on-exceed="handleExceed"
        :show-file-list="false"
    >
      <el-button type="success">导入员工</el-button>
    </el-upload>
    <el-button type="warning" size="default" @click="handleUserExport">导出员工</el-button>

    <el-button type="warning" size="default" @click="handleSignExport">导出考勤</el-button>
    <!-- 添加用户 -->
    <el-drawer v-model="addUserDrawer" title="添加用户" :with-header="true">
      <div class="add-user-item">
        <span class="input-label">用户名: </span>
        <el-input v-model="newUser.username" placeholder="请设置用户名"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">密码: </span>
        <el-input v-model="newUser.password" placeholder="请设置密码"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">角色: </span>
        <el-select v-model="newUser.role" placeholder="请选择角色">
          <el-option label="管理员" value=1></el-option>
          <el-option label="普通用户" value=0></el-option>
        </el-select>
      </div>
      <div class="add-user-item">
        <span class="input-label">邮箱: </span>
        <el-input v-model="newUser.email" placeholder="请设置邮箱"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">手机号: </span>
        <el-input v-model="newUser.phone" placeholder="请设置手机号"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">姓名: </span>
        <el-input v-model="newUser.realName" placeholder="请设置姓名"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">职位: </span>
        <el-input v-model="newUser.jobTitle" placeholder="请设置职位"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">入职日期: </span>
        <el-input v-model="newUser.hireDate" placeholder="请设置入职日期"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">部门名称: </span>
        <el-input v-model="newUser.name" placeholder="请设置部门"></el-input>
      </div>
      <div class="add-user-item">
        <el-button class="add-user-btn" type="primary" size="default" @click="saveNewUser">添加用户</el-button>
      </div>
    </el-drawer>
    <!-- 修改用户 -->
    <el-drawer v-model="updateUserDrawer" title="修改用户" :with-header="true">
      <input v-model="updateUserData.id" type="text" hidden></input>
      <div class="add-user-item">
        <span class="input-label">用户名: </span>
        <el-input v-model="updateUserData.username" placeholder="请修改用户名"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">密码: </span>
        <el-input v-model="updateUserData.password" placeholder="请修改密码"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">角色: </span>
        <el-select v-model="updateUserData.role" placeholder="请选择角色">
          <el-option label="管理员" value=1></el-option>
          <el-option label="普通用户" value=0></el-option>
        </el-select>
      </div>
      <div class="add-user-item">
        <span class="input-label">邮箱: </span>
        <el-input v-model="updateUserData.email" placeholder="请设置邮箱"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">手机号: </span>
        <el-input v-model="updateUserData.phone" placeholder="请设置手机号"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">姓名: </span>
        <el-input v-model="updateUserData.realName" placeholder="请设置姓名"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">职位: </span>
        <el-input v-model="updateUserData.jobTitle" placeholder="请设置职位"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">部门名称: </span>
        <el-input v-model="updateUserData.name" placeholder="请设置部门"></el-input>
      </div>
      <div class="add-user-item">
        <el-button class="add-user-btn" type="primary" size="default" @click="updateUserById">修改信息</el-button>
      </div>
    </el-drawer>
    <!-- 用户详情 -->
    <el-drawer v-model="userDetailsDrawer" title="用户详情" :with-header="true" :before-close="handleUserDetailsDrawerClose" :key="refCount">
      <UserDetailsView :userData="detailUserData"/>
    </el-drawer>
  </div>
  <div class="user-list">
    <el-table
        :data="userList"
        border
        class="user-table"
    >
      <el-table-column prop="userId" label="ID" align="center" width="100"/>
      <el-table-column prop="username" label="用户名" align="center" min-width="100" max-width="150"/>
      <el-table-column prop="email" label="邮箱" align="center">
      </el-table-column>
      <el-table-column prop="phone" label="手机号" align="center" min-width="200"/>
      <el-table-column prop="name" label="所属部门" align="center" min-width="200" max-width="250"/>
      <el-table-column label="操作" align="center" width="200" v-if="userRole === 1">
        <template #default="scope">
          <div class="operation-btns">
            <el-button type="primary" size="small" @click="openUserDetailsDrawer(scope.row)">详情</el-button>
            <el-button type="success" size="small" @click="openUpdateUserDrawer(scope.row)">修改</el-button>
            <el-button type="danger" size="small"
                       @click="deleteUserById(scope.row.userId)">删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px; text-align: center">
      <el-pagination
          :page-size="pageForm.size"
          :total="pageForm.total"
          :current-page="pageForm.page"
          @current-change="handleCurrentChange"
          layout="prev, pager, next"
      />
    </div>
  </div>
</template>

<style scoped>
.user-operation {
  margin-bottom: 20px;
}

.user-table {
  position: relative;
}

.add-user-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.input-label {
  margin-right: 10px;
  width: 80px;
  text-align: right;
  font-weight: bold;
  color: #606266;
}

.add-user-btn {
  width: 100%;
  margin-top: 50px;
}

.operation-btns {
  display: flex;
  justify-content: center;
}

</style>
